<template>
  <div class="customer-detail-container" :key="`customer-${customerId}-${$route.fullPath}`">
    <!-- 页面头部导航 -->
    <div class="page-header">
      <el-page-header @back="goBack" :content="`客户详情: ${customerData.customer_id || '加载中...'}`">
      </el-page-header>
      <div class="header-actions">
        <el-button type="primary" @click="runChurnPrediction" :loading="predicting">流失预测</el-button>
        <el-button type="success" @click="openRetentionDialog">制定挽留方案</el-button>
      </div>
    </div>

    <div v-loading="loading" class="content-container">
      <!-- 客户基本信息 -->
      <div class="basic-info">
        <div class="info-header">
          <div class="customer-avatar">{{ getInitials(customerData.customer_id) }}</div>
          <div class="customer-info">
            <div class="customer-id">{{ customerData.customer_id }}</div>
            <div class="customer-tags">
              <el-tag size="small" :type="getInternetServiceTagType()">
                {{ getInternetServiceLabel() }}
              </el-tag>
              <el-tag size="small" type="success" v-if="customerData.partner">有伴侣</el-tag>
              <el-tag size="small" type="info" v-else>单身</el-tag>
              <el-tag size="small" type="warning" v-if="customerData.dependents">有家属</el-tag>
            </div>
          </div>
        </div>

        <div class="risk-area">
          <div class="risk-label" :class="getRiskClass()">{{ getRiskLabel() }}</div>
          <div class="risk-actions">
            <el-button type="danger" plain size="small" @click="runChurnPrediction" :loading="predicting">
              流失预测
            </el-button>
            <el-button type="success" plain size="small" @click="openRetentionDialog">制定挽留方案</el-button>
          </div>
        </div>
      </div>

      <!-- 客户基本信息卡片 -->
      <el-card class="detail-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>客户基本信息</span>
            <el-button type="primary" size="small" plain>编辑</el-button>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="customer-avatar-large">
              <el-avatar :size="100">
                {{ getInitials() }}
              </el-avatar>
              <div class="risk-badge" :class="getRiskClass()">
                {{ getRiskLabel() }}
              </div>
            </div>
          </el-col>
          <el-col :span="16">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="客户ID">{{ customerData.customer_id }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ customerData.gender_display || customerData.gender }}</el-descriptions-item>
              <el-descriptions-item label="老年客户">{{ customerData.senior_citizen ? '是' : '否' }}</el-descriptions-item>
              <el-descriptions-item label="伴侣">{{ customerData.partner ? '是' : '否' }}</el-descriptions-item>
              <el-descriptions-item label="经济独立">{{ customerData.dependents ? '是' : '否' }}</el-descriptions-item>
              <el-descriptions-item label="使用时长">{{ customerData.tenure }} 个月</el-descriptions-item>
              <el-descriptions-item label="电子账单">{{ customerData.paperless_billing ? '是' : '否' }}</el-descriptions-item>
              <el-descriptions-item label="支付方式">{{ customerData.payment_method_display || customerData.payment_method }}</el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </el-card>

      <!-- 服务信息卡片 -->
      <el-card class="detail-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>服务使用信息</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-descriptions border>
              <el-descriptions-item label="合同类型">
                <el-tag :type="getContractTagType()">{{ customerData.contract_display || customerData.contract }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="电话服务">
                {{ customerData.phone_service ? '是' : '否' }}
              </el-descriptions-item>
              <el-descriptions-item label="多线服务">
                {{ customerData.multiple_lines || '无' }}
              </el-descriptions-item>
              <el-descriptions-item label="互联网服务">
                <el-tag :type="getInternetServiceTagType()">{{ getInternetServiceLabel() }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="12">
            <el-descriptions border>
              <el-descriptions-item label="在线安全服务">
                {{ customerData.online_security || '无' }}
              </el-descriptions-item>
              <el-descriptions-item label="在线备份">
                {{ customerData.online_backup || '无' }}
              </el-descriptions-item>
              <el-descriptions-item label="设备保护">
                {{ customerData.device_protection || '无' }}
              </el-descriptions-item>
              <el-descriptions-item label="技术支持">
                {{ customerData.tech_support || '无' }}
              </el-descriptions-item>
              <el-descriptions-item label="流媒体电视">
                {{ customerData.streaming_tv || '无' }}
              </el-descriptions-item>
              <el-descriptions-item label="流媒体电影">
                {{ customerData.streaming_movies || '无' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </el-card>

      <!-- 消费信息卡片 -->
      <el-row :gutter="20" class="consumption-row">
        <el-col :span="12">
          <el-card class="detail-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>消费统计</span>
              </div>
            </template>
            <el-descriptions border :column="1">
              <el-descriptions-item label="月费用">
                <span class="price-value">¥{{ Number(customerData.monthly_charges)?.toFixed(2) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="总费用">
                <span class="price-value">¥{{ Number(customerData.total_charges)?.toFixed(2) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="客户价值">
                <el-tag size="large" type="success" effect="dark">
                  {{ getCustomerValueLabel() }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="detail-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>消费趋势</span>
              </div>
            </template>
            <div ref="consumptionChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 调试信息 -->
      <el-card v-if="predictionResult" class="detail-card" shadow="hover" style="margin-bottom: 20px; background: #f9f9f9;">
        <template #header>
          <div class="card-header">
            <span>预测数据调试</span>
          </div>
        </template>
        <div style="font-size: 12px; color: #666;">
          <p><strong>原始预测数据:</strong> {{ JSON.stringify(predictionResult, null, 2) }}</p>
          <p><strong>概率值:</strong> {{ predictionResult.probability }}</p>
          <p><strong>概率类型:</strong> {{ typeof predictionResult.probability }}</p>
          <p><strong>显示概率:</strong> {{ getProbabilityDisplay() }}%</p>
          <p><strong>百分比值:</strong> {{ getProbabilityPercentage() }}</p>
        </div>
      </el-card>

      <!-- 流失预测结果 -->
      <el-card v-if="predictionResult" class="detail-card prediction-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>流失预测结果</span>
            <el-tag :type="predictionResult.risk_level === 'high' ? 'danger' : predictionResult.risk_level === 'medium' ? 'warning' : 'success'">
              {{ predictionResult.risk_level === 'high' ? '高风险' : predictionResult.risk_level === 'medium' ? '中风险' : '低风险' }}
            </el-tag>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="prediction-score">
              <div class="score-label">流失概率</div>
              <div class="score-value">{{ getProbabilityDisplay() }}%</div>
              <el-progress
                :percentage="getProbabilityPercentage()"
                :color="getProgressColor(getProbabilityPercentage() / 100)"
                :stroke-width="8"
              />
            </div>
          </el-col>
          <el-col :span="12">
            <div class="prediction-factors">
              <div class="factors-title">主要影响因素</div>
              <div class="factors-list">
                <div v-for="factor in predictionResult.key_factors" :key="factor.factor" class="factor-item">
                  <span class="factor-name">{{ factor.factor }}</span>
                  <span class="factor-impact" :class="factor.impact > 0 ? 'positive' : 'negative'">
                    {{ factor.impact > 0 ? '+' : '' }}{{ (factor.impact * 100).toFixed(1) }}%
                  </span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 推荐挽留策略 -->
      <el-card class="detail-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>推荐挽留策略</span>
          </div>
        </template>
        <el-table :data="retentionStrategies" style="width: 100%">
          <el-table-column prop="strategy" label="策略" width="180"></el-table-column>
          <el-table-column prop="description" label="描述"></el-table-column>
          <el-table-column prop="effectiveness" label="预估效果" width="150">
            <template #default="scope">
              <el-progress
                :percentage="scope.row.effectiveness"
                :color="getEffectivenessColor(scope.row.effectiveness)"
                :stroke-width="6"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 挽留方案制定对话框 -->
    <el-dialog v-model="retentionDialogVisible" title="制定挽留方案" width="600px">
      <el-form :model="retentionForm" label-width="100px">
        <el-form-item label="策略类型">
          <el-select v-model="retentionForm.type" placeholder="请选择策略类型">
            <el-option label="套餐优惠" value="discount"></el-option>
            <el-option label="套餐升级" value="upgrade"></el-option>
            <el-option label="增值服务" value="service"></el-option>
            <el-option label="专属客服" value="support"></el-option>
            <el-option label="设备更新" value="device"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="策略描述">
          <el-input v-model="retentionForm.description" type="textarea" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="优惠力度">
          <el-slider v-model="retentionForm.discount" :step="5" :marks="discountMarks"></el-slider>
        </el-form-item>
        <el-form-item label="有效期限">
          <el-select v-model="retentionForm.period" placeholder="请选择有效期">
            <el-option label="1个月" :value="1"></el-option>
            <el-option label="3个月" :value="3"></el-option>
            <el-option label="6个月" :value="6"></el-option>
            <el-option label="12个月" :value="12"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="retentionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="applyRetentionStrategy">应用策略</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 引入API模块
import { getCustomerDetail, getCustomerDetailDebug } from '@/api/modules/customer'
import { predictCustomerById as predictChurn } from '@/api/modules/prediction'

const route = useRoute()
const router = useRouter()
const customerId = ref(route.params.id)

// 响应式数据
const loading = ref(false)
const predicting = ref(false)
const customerData = reactive({})
const predictionResult = ref(null)

// 图表引用
const consumptionChart = ref(null)

// 挽留方案对话框
const retentionDialogVisible = ref(false)
const retentionForm = reactive({
  type: 'discount',
  description: '',
  discount: 15,
  period: 3
})

const discountMarks = {
  0: '0%',
  25: '25%',
  50: '50%',
  75: '75%',
  100: '100%'
}

// 推荐挽留策略数据
const retentionStrategies = ref([
  {
    strategy: '套餐优惠',
    description: '提供月费折扣，降低客户成本负担',
    effectiveness: 75
  },
  {
    strategy: '服务升级',
    description: '免费升级到更高速的网络服务',
    effectiveness: 68
  },
  {
    strategy: '增值服务',
    description: '赠送流媒体服务或设备保护',
    effectiveness: 62
  },
  {
    strategy: '专属客服',
    description: '提供一对一专属客服支持',
    effectiveness: 55
  },
  {
    strategy: '长期合约',
    description: '签订长期合约享受更多优惠',
    effectiveness: 48
  }
])

// 检查客户ID是否存在的函数
const checkCustomerId = () => {
  if (!customerId.value) {
    console.error('客户ID缺失，将重定向到客户列表页面')
    ElMessage.error('客户ID缺失，无法查看客户详情')
    router.push('/customer/list')
    return false
  }
  return true
}

// 辅助函数
const getInitials = (customerId) => {
  return customerId ? customerId.substring(0, 2).toUpperCase() : '?'
}

const getRiskClass = () => {
  if (!customerData.churn_risk) return 'risk-unknown'
  return {
    'low': 'risk-low',
    'medium': 'risk-medium',
    'high': 'risk-high'
  }[customerData.churn_risk] || 'risk-unknown'
}

const getRiskLabel = () => {
  if (!customerData.churn_risk) return '未评估'
  return {
    'low': '低风险',
    'medium': '中风险',
    'high': '高风险'
  }[customerData.churn_risk] || '未知'
}

const getInternetServiceTagType = () => {
  const service = customerData.internet_service
  if (service === 'Fiber optic') return 'success'
  if (service === 'DSL') return 'warning'
  return 'info'
}

const getInternetServiceLabel = () => {
  return customerData.internet_service_display || customerData.internet_service || '无'
}

const getContractTagType = () => {
  const contract = customerData.contract
  if (contract === 'Two year') return 'success'
  if (contract === 'One year') return 'warning'
  return 'danger'
}

const getCustomerValueLabel = () => {
  const totalCharges = Number(customerData.total_charges) || 0
  if (totalCharges > 5000) return '高价值客户'
  if (totalCharges > 2000) return '中价值客户'
  return '普通客户'
}

const getProgressColor = (percentage) => {
  if (percentage > 70) return '#f56c6c'
  if (percentage > 40) return '#e6a23c'
  return '#67c23a'
}

const getEffectivenessColor = (percentage) => {
  if (percentage > 70) return '#67c23a'
  if (percentage > 50) return '#e6a23c'
  return '#f56c6c'
}

// 获取概率显示值
const getProbabilityDisplay = () => {
  if (!predictionResult.value) {
    console.log('没有预测结果')
    return '0.0'
  }

  // 尝试多个可能的字段名
  const probability = predictionResult.value.probability ||
                     predictionResult.value.churn_probability ||
                     customerData.churn_probability || 0

  console.log('获取到的概率值:', probability, '类型:', typeof probability)

  // 确保是有效数字
  const numValue = Number(probability)
  if (isNaN(numValue)) {
    console.warn('概率值不是有效数字:', probability)
    return '0.0'
  }

  // 如果是0-1之间的小数，转换为百分比
  if (numValue <= 1) {
    const result = (numValue * 100).toFixed(1)
    console.log('转换后的百分比显示:', result)
    return result
  }

  // 如果已经是百分比形式
  const result = numValue.toFixed(1)
  console.log('直接显示的百分比:', result)
  return result
}

// 获取概率百分比值
const getProbabilityPercentage = () => {
  if (!predictionResult.value) {
    console.log('没有预测结果，返回0')
    return 0
  }

  const probability = predictionResult.value.probability ||
                     predictionResult.value.churn_probability ||
                     customerData.churn_probability || 0

  console.log('获取到的概率值(百分比):', probability)

  const numValue = Number(probability)
  if (isNaN(numValue)) {
    console.warn('概率值不是有效数字(百分比):', probability)
    return 0
  }

  // 如果是0-1之间的小数，转换为百分比
  if (numValue <= 1) {
    const result = numValue * 100
    console.log('转换后的百分比值:', result)
    return result
  }

  // 如果已经是百分比形式，直接返回
  console.log('直接返回的百分比值:', numValue)
  return numValue
}

// 获取客户数据
const fetchCustomerData = async () => {
  if (!checkCustomerId()) return
  
  loading.value = true
  
  try {
    const response = await getCustomerDetail(customerId.value)
    
    if (response && response.success && response.data) {
      // 清空之前的数据
      Object.keys(customerData).forEach(key => {
        delete customerData[key]
      })
      // 将API返回的数据赋值给customerData
      Object.assign(customerData, response.data)
      console.log('客户详情获取成功:', customerData)

      // 初始化图表
      nextTick(() => {
        initCharts()
      })
    } else {
      console.error('获取客户详情失败:', response)
      ElMessage.error(response?.message || '获取客户详情失败')
      // 返回客户列表
      router.push('/customer/list')
    }
  } catch (error) {
    console.error('获取客户详情错误:', error)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 添加调试功能
const debugCustomerData = async () => {
  if (!checkCustomerId()) return
  
  try {
    const response = await getCustomerDetailDebug(customerId.value)
    console.log('调试响应:', response)
    
    if (response && response.success && response.data) {
      Object.assign(customerData, response.data)
      console.log('调试数据获取成功:', customerData)
    } else {
      console.error('调试请求失败:', response)
    }
  } catch (error) {
    console.error('调试请求错误:', error)
  }
}

// 运行流失预测
const runChurnPrediction = async () => {
  if (!checkCustomerId()) return

  predicting.value = true

  try {
    console.log('开始预测，客户ID:', customerId.value)
    const response = await predictChurn(customerId.value)
    console.log('预测API响应:', response)

    if (response && response.success) {
      ElMessage.success('流失预测完成')

      // 保存预测结果，确保数据格式正确
      const data = response.data
      console.log('预测数据:', data)

      // 处理概率值
      let probability = 0
      if (data.probability !== undefined && data.probability !== null) {
        probability = Number(data.probability)
        if (isNaN(probability)) {
          console.warn('概率值不是有效数字:', data.probability)
          probability = 0
        }
      }

      predictionResult.value = {
        ...data,
        // 确保概率字段存在且为数字
        probability: probability,
        churn_probability: probability,
        // 模拟一些影响因素数据（如果后端没有返回）
        key_factors: data.key_factors || [
          { factor: '使用时长', impact: customerData.tenure < 12 ? 0.15 : -0.15 },
          { factor: '月费用', impact: customerData.monthly_charges > 70 ? 0.08 : -0.05 },
          { factor: '合同类型', impact: customerData.contract === 'Month-to-month' ? 0.12 : -0.12 },
          { factor: '互联网服务', impact: customerData.internet_service === 'Fiber optic' ? 0.05 : -0.03 }
        ]
      }

      console.log('处理后的预测结果:', predictionResult.value)

      // 同时更新客户数据中的风险信息
      if (data.risk_level) {
        customerData.churn_risk = data.risk_level
      }
      if (probability !== undefined) {
        customerData.churn_probability = probability
      }
    } else {
      console.error('预测失败:', response)
      ElMessage.error(response?.message || '预测失败')
    }
  } catch (error) {
    console.error('预测错误:', error)
    ElMessage.error('预测服务暂时不可用')
  } finally {
    predicting.value = false
  }
}

// 打开挽留方案对话框
const openRetentionDialog = () => {
  retentionDialogVisible.value = true
}

// 应用挽留策略
const applyRetentionStrategy = () => {
  ElMessage.success('挽留策略已应用')
  retentionDialogVisible.value = false
}

// 返回上一页
const goBack = () => {
  window.location.href = '/customer/list'
}

// 初始化图表
const initCharts = () => {
  if (consumptionChart.value) {
    initConsumptionChart()
  }
}

// 初始化消费趋势图表
const initConsumptionChart = () => {
  const chart = echarts.init(consumptionChart.value)

  const option = {
    title: {
      text: '消费趋势',
      left: 'center',
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      name: '费用(¥)'
    },
    series: [{
      name: '月费用',
      type: 'line',
      data: [
        customerData.monthly_charges * 0.8,
        customerData.monthly_charges * 0.9,
        customerData.monthly_charges * 1.1,
        customerData.monthly_charges,
        customerData.monthly_charges * 1.05,
        customerData.monthly_charges
      ],
      smooth: true,
      itemStyle: {
        color: '#409EFF'
      }
    }]
  }

  chart.setOption(option)

  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 强制初始化数据
const forceInit = () => {
  console.log('强制初始化，当前路由参数:', route.params.id);
  const currentId = route.params.id;
  if (currentId) {
    customerId.value = currentId;
    // 清空之前的数据
    Object.keys(customerData).forEach(key => {
      delete customerData[key]
    })
    // 立即获取数据
    fetchCustomerData();

    // 延迟1秒后尝试调试请求
    setTimeout(() => {
      if (Object.keys(customerData).length <= 1) {
        debugCustomerData()
      }
    }, 1000)
  }
}

// 监听路由参数变化
watch(() => route.params.id, (newId, oldId) => {
  console.log('路由参数变化:', oldId, '->', newId);
  if (newId && newId !== oldId) {
    forceInit();
  }
}, { immediate: false })

// 监听整个路由变化
watch(() => route.fullPath, (newPath, oldPath) => {
  console.log('路由路径变化:', oldPath, '->', newPath);
  if (newPath.includes('/customer/detail/')) {
    forceInit();
  }
}, { immediate: true })

// 生命周期钩子
onMounted(() => {
  console.log('组件已挂载，客户ID:', customerId.value);
  console.log('当前路由:', route.fullPath);

  // 强制初始化
  setTimeout(() => {
    forceInit();
  }, 100);
})
</script>

<style lang="scss" scoped>
.customer-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.content-container {
  min-height: 400px;
}

.basic-info {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 20px;
  color: white;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
    opacity: 0.3;
  }

  .info-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    position: relative;
    z-index: 1;

    .customer-avatar {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.2);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      font-weight: bold;
      margin-right: 20px;
      backdrop-filter: blur(10px);
    }

    .customer-info {
      flex: 1;

      .customer-id {
        font-size: 28px;
        font-weight: bold;
        margin-bottom: 8px;
      }

      .customer-tags {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
      }
    }
  }

  .risk-area {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    z-index: 1;

    .risk-label {
      padding: 8px 16px;
      border-radius: 20px;
      font-weight: bold;
      font-size: 14px;

      &.risk-low {
        background: rgba(103, 194, 58, 0.2);
        color: #67c23a;
        border: 1px solid rgba(103, 194, 58, 0.3);
      }

      &.risk-medium {
        background: rgba(230, 162, 60, 0.2);
        color: #e6a23c;
        border: 1px solid rgba(230, 162, 60, 0.3);
      }

      &.risk-high {
        background: rgba(245, 108, 108, 0.2);
        color: #f56c6c;
        border: 1px solid rgba(245, 108, 108, 0.3);
      }

      &.risk-unknown {
        background: rgba(144, 147, 153, 0.2);
        color: #909399;
        border: 1px solid rgba(144, 147, 153, 0.3);
      }
    }

    .risk-actions {
      display: flex;
      gap: 12px;
    }
  }
}

.detail-card {
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    font-size: 16px;
  }
}

.customer-avatar-large {
  text-align: center;
  position: relative;

  .risk-badge {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: bold;

    &.risk-low {
      background: #f0f9ff;
      color: #67c23a;
      border: 1px solid #67c23a;
    }

    &.risk-medium {
      background: #fdf6ec;
      color: #e6a23c;
      border: 1px solid #e6a23c;
    }

    &.risk-high {
      background: #fef0f0;
      color: #f56c6c;
      border: 1px solid #f56c6c;
    }

    &.risk-unknown {
      background: #f4f4f5;
      color: #909399;
      border: 1px solid #909399;
    }
  }
}

.consumption-row {
  margin-bottom: 20px;
}

.price-value {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.prediction-card {
  border: 2px solid #e6f7ff;
  background: linear-gradient(135deg, #e6f7ff 0%, #f6ffed 100%);

  .prediction-score {
    text-align: center;

    .score-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
    }

    .score-value {
      font-size: 36px;
      font-weight: bold;
      color: #409EFF;
      margin-bottom: 16px;
    }
  }

  .prediction-factors {
    .factors-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 12px;
      color: #333;
    }

    .factors-list {
      .factor-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .factor-name {
          font-size: 14px;
          color: #666;
        }

        .factor-impact {
          font-weight: bold;
          font-size: 14px;

          &.positive {
            color: #f56c6c;
          }

          &.negative {
            color: #67c23a;
          }
        }
      }
    }
  }
}
</style>
